<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备" prop="level">
        <el-select
          v-model="queryParams.questionEquipmentId"
          placeholder="请选择设备"
          clearable
        >
          <el-option
            v-for="item in bankList"
            :key="item.id"
            :label="item.equipmentName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:video:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:video:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:video:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:video:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="videoList"
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="设备" align="center" prop="equipmentName" />
      <!-- <el-table-column label="${comment}" align="center" prop="content" />
      <el-table-column label="${comment}" align="center" prop="url" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:video:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:video:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改视频对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容简介" prop="content">
          <el-input v-model="form.content" placeholder="请输入内容简介" />
          <!-- <editor v-model="form.content" :min-height="192"/> -->
        </el-form-item>
        <el-form-item
          label="设备"
          v-model="form.questionEquipmentId"
          prop="questionEquipmentId"
        >
          <el-select v-model="form.questionEquipmentId" placeholder="请选择">
            <el-option
              v-for="item in bankList"
              :key="item.id"
              :label="item.equipmentName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频" prop="video">
          <!-- <fileUpload v-model="form.url"/> -->
          <el-upload
            class="upload-demo"
            :action="imgupdate"
            :headers="headers"
            :on-success="handleChange"
            :before-upload="beforeUploadVideo"
            :on-remove="remove"
            :limit="1"
            :file-list="fileList"
          >
            <!-- limit="1" -->
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              最多可以上传1个视频，建议大小50M，推荐格式mp4
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <tree-transfer
          :title="titles"
          :from_data="fromData"
          :to_data="toData"
          :defaultProps="{ label: 'label' }"
          @add-btn="add"
          @remove-btn="remove"
          :mode="mode"
          height="540px"
          filter
          openAll
        >
        </tree-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listVideo,
  getVideo,
  delVideo,
  addVideo,
  updateVideo,
} from "@/api/exam/video";
import { getToken } from "@/utils/auth";
import treeTransfer from "el-tree-transfer"; // 引入
import { treeselect } from "@/api/system/dept";
import { listBank } from "@/api/exam/bank";

export default {
  name: "Video",
  components: { treeTransfer },

  data() {
    return {
      determine: [],
      titles: ["未分配列表", "已分配列表"],
      mode: "transfer", // transfer addressList
      fromData: [],
      toData: [],
      imgupdate: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频表格数据
      videoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {
            required: true,
            message: "请输入标题",
            trigger: "blur",
          },
        ],
      },
      //视频列表
      fileList: [],
      bankList: [],
    };
  },
  created() {
    this.getList();
    //设备
    listBank(null).then((response) => {
      console.log(response.rows);
      this.bankList = response.rows;
    });

  },
  methods: {
    /** 查询视频列表 */
    getList() {
      this.loading = true;
      listVideo(this.queryParams).then((response) => {
        this.videoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        url: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        shareId: null,
        treeTransferRight: null,
      };
      this.fileList = [];
      this.fromData = [];
      this.toData = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加视频";
      //下拉列表
      treeselect().then((response) => {
        this.fromData = response.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getVideo(id).then((response) => {
        console.log("123",response.data);
        this.form = response.data;
        if (response.data.url != "") {
          this.fileList.push({
            name: response.data.title,
            url: response.data.url,
          });

        }
        this.determine = response.data.shareId.split(",");
        this.toData = JSON.parse(response.data.treeTransferRight);
        treeselect().then((response) => {
          console.log("下拉框显示", response);
          this.fromData = this.handlerTree(response.data,this.toData);
        });

        this.open = true;
        this.title = "修改视频";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (this.fileList.length > 0) {
          this.form.url = this.fileList[0].url;
        } else {
          this.form.url = "";
        }

        this.form.shareId = this.determine.join(",");
        this.form.treeTransferRight = JSON.stringify(this.toData);
        if (valid) {
          if (this.form.id != null) {
            updateVideo(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVideo(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除视频编号为"' + ids + '"的数据项？')
        .then(function () {
          return delVideo(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/video/export",
        {
          ...this.queryParams,
        },
        `video_${new Date().getTime()}.xlsx`
      );
    },
    //视频
    handleChange(response, file, fileList) {
      this.fileList.push({ name: file.name, url: response.fileName });
    },
    //删除
    remove(file, fileList) {
      console.log("显示", file);
      this.fileList.map((item, index) => {
        //移除图片在表单中的数据
        if (item.url === file.url) this.fileList.splice(index, 1);
      });
      console.log("寄哪里", this.fileList);
    },
    beforeUploadVideo(file) {
      console.log("ianshi", file);
      var fileSize = file.size / 1024 / 1024 < 1000;
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb",
          "video/mov",
        ].indexOf(file.type) == -1
      ) {
        this.$modal.msgSuccess("请上传正确的视频格式");
        return false;
      }
      if (!fileSize) {
        this.$modal.msgSuccess("视频大小不能超过100MB");
        return false;
      }
    },

    // 监听穿梭框组件添加
    add(fromData, toData, obj) {
      // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
      // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
      console.log("右fromData:", fromData);
      console.log("右toData:", toData);
      console.log("右obj:", obj);
      console.log("右this.fromData:", this.fromData);
      console.log("右this.toData:", this.toData);
      obj.keys.map((item) => {
        this.determine.push(item);
      });
      console.log("保存数据", this.determine);
    },
    // 监听穿梭框组件移除
    remove(fromData, toData, obj) {
      // 树形穿梭框模式transfer时，返回参数为左侧树移动后数据、右侧树移动后数据、移动的{keys,nodes,halfKeys,halfNodes}对象
      // 通讯录模式addressList时，返回参数为右侧收件人列表、右侧抄送人列表、右侧密送人列表
      console.log("左fromData:", fromData);
      console.log("左toData:", toData);
      console.log("左obj:", obj);
      obj.keys.map((item) => {
        this.determine.map((dte, index) => {
          //移除图片在表单中的数据
          if (item === dte) this.determine.splice(index, 1);
        });
      });
      console.log("删除后数据", this.determine);
    },

    // 根据已选择页面的权限 递归处理数据
    //data 所有的树形数据  selData 已选择的树形数据
    handlerTree (data, selData) {
      for (let i = data.length - 1; i >= 0; i--) {
        for (let j = selData.length - 1; j >= 0; j--) {
          if (data[i] && (data[i].id === selData[j].id)) {
            // 当id相等可以删除的情况 即：没有子级可以删除；
            if (!data[i].children && !selData[j].children) {
              data.splice(i, 1)
            } else {
              this.handlerTree(data[i].children, selData[j].children)
            }
          }
        }
      }
      return data;
    },
  },
};
</script>
